<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use think\Db;
use app\admin\model\Admin as AdminModel;

class Slide extends Common
{	
    public function index()
    {	

    	// 获取表单上传文件 例如上传了001.jpg
	    $file = request()->file('image');
	    
	    // 移动到框架应用根目录/public/uploads/ 目录下
	    if($file){
	        $slide = $file->validate(['size'=>5242880,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public/uploads/slide','');	        
	        if($slide){
	            $image='/public/uploads/slide/'.$slide->getFilename();
	            $_POST['image'] = $image;
	        }else{
	            // 上传失败获取错误信息
	            echo $file->getError();
	        }
	    }

	    if(request()->isPost()){
    		$res = db('slide')->insert($_POST);
    		if($res){
    			$this->success('添加成功');
    		}else{
    			$this->error('添加失败');
    		}
    	}

    	$list = db('slide')->order('sort')->select();
    	$this->assign('list',$list);
        return view();
    }

    public function del($id) 
    {
    	$image = db('slide')->where('id',$id)->value('image');
    	$res = db('slide')->where('id',$id)->delete();
    	if ($res) {
    		$thumbpath=$_SERVER['DOCUMENT_ROOT'].$image;
	    	if(file_exists($thumbpath)){
            	@unlink($thumbpath);
            }
    		$this->success('删除成功');
    	}else{
    		$this->error('删除失败');
    	}
    }

    public function edit($id)
    {
    	$list = db('slide')->where('id',$id)->find();
    	$this->assign('list',$list);

    	// 获取表单上传文件 例如上传了001.jpg
	    $file = request()->file('image');
	    // 移动到框架应用根目录/public/uploads/ 目录下
	    if($file){
	        $slide = $file->validate(['size'=>5242880,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public/uploads/slide','');	        
	        if($slide){
	            $image='/public/uploads/slide/'.$slide->getFilename();
	            $_POST['image'] = $image;
	            $thumbpath=$_SERVER['DOCUMENT_ROOT'].$list['image'];
		    	if(file_exists($thumbpath)){
	            	@unlink($thumbpath);
	            }
	        }else{
	            // 上传失败获取错误信息
	            echo $file->getError();
	        }
	    }

	    if(request()->isPost()){
			$res = Db::name('slide')->update($_POST);
    		if($res){
    			$this->success('修改成功','Slide/index');
    		}else{
    			$this->error('修改失败');
    		}
    	}

    	return view();
    }

}
